// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import Client from '@api/meeting/api/MeetingInfoApi'

import ListClass from '@api/meeting/model/MeetingInfoReq'
import OneClass from '@api/meeting/model/MeetingInfoDetailReq'
import DelClass from '@api/meeting/model/MeetingInfoDeleteReq'
import BaseClass from '@api/meeting/model/MeetingInfoDto'

const AddClass = ListClass
const EditClass = ListClass

const CLIENT = CORE.grpcCLIENT(Client)
const BASE = [BaseClass, 'dto']

const transTime = (time) => CORE.timeStr(time).slice(11, -3)
const transNum = (time) => +time.replace(':0', '0').replace(':3', '5')

// ============================== 导出远程接口 ============================== //

export default {
  // —————————————————————————————— 单项 —————————————————————————————— //

  async getOne(one, TIP = '查询详情') {
    const DTO = CORE.grpcDTO(OneClass, one)
    const resp = await CORE.grpc(TIP, CLIENT, 'meetingInfoDetail', DTO)
    return { ...one, ...resp.dto }
  },
  transOne(obj, { commit }) {
    Object.assign(obj, { tagMap: {}, recordMap: {} })
    const record_list = (obj.recordDtos || []).map((record) => {
      const [begin, end] = [transTime(record.startTime), transTime(record.endTime)]
      record.times = `${begin} 至 ${end}`
      const count = (transNum(end) - transNum(begin)) / 50 | 0 // 半小时的个数
      Array(count).fill().forEach((_, i) => {
        const time = transTime(record.startTime + i * 1800000)
        obj.tagMap[time] = count === 1 ? 'single' : !i ? 'first' : i === count - 1 ? 'last' : 'middle'
        obj.recordMap[time] = record.id
      })
      return record
    })
    commit('record/setList', record_list)
    return obj
  },

  // —————————————————————————————— 增 —————————————————————————————— //

  async add(one, TIP = '新增') {
    const DTO = CORE.grpcDTO(AddClass, one, BASE)
    await CORE.grpc(TIP, CLIENT, 'meetingInfoSave', DTO)
    return CORE.grpcOK(TIP)
  },

  // —————————————————————————————— 改 —————————————————————————————— //

  async edit(one, TIP = '修改') {
    const DTO = CORE.grpcDTO(EditClass, one, BASE)
    await CORE.grpc(TIP, CLIENT, 'meetingInfoUpdate', DTO)
    return CORE.grpcOK(TIP)
  },

  // —————————————————————————————— 删 —————————————————————————————— //

  async del({ id }, TIP = '删除') {
    const DTO = CORE.grpcDTO(DelClass, { ids: [id] })
    await CORE.grpc(TIP, CLIENT, 'meetingInfoDelete', DTO)
    return CORE.grpcOK(TIP)
  },
}
